<template>
  <div class="demand-management">
    <div class="header">
      <h2>需求管理</h2>
    </div>
    
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="需求标题">
          <el-input style="width: 200px;" 
            v-model="searchForm.title"
            placeholder="请输入需求标题"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="需求状态">
          <el-select style="width: 120px;"
            v-model="searchForm.status"
            placeholder="请选择需求状态"
            clearable
          >
            <el-option label="待审核" value="0" />
            <el-option label="审核通过" value="1" />
            <el-option label="审核拒绝" value="2" />
            <el-option label="已发布" value="3" />
            <el-option label="已接单" value="4" />
            <el-option label="进行中" value="5" />
            <el-option label="已完成" value="6" />
            <el-option label="已关闭" value="7" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="openAddDialog">新增需求</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 数据表格 -->
    <div class="table-area">
      <el-table
        v-loading="loading"
        :data="demandData"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="需求ID" width="80" />
        
        <el-table-column prop="id" label="需求ID" width="80" />
        <el-table-column prop="title" label="需求标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="description" label="需求描述" min-width="250" show-overflow-tooltip />
        <el-table-column prop="userName" label="发布用户名" width="120" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.userName || '未知用户' }}
          </template>
        </el-table-column>
        <el-table-column prop="budget" label="预算" width="100">
          <template #default="scope">
            {{ scope.row.budget || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="deadline" label="截止时间" width="180" />
        <el-table-column prop="status" label="需求状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditRemark" label="审核备注" min-width="200" show-overflow-tooltip />
        <el-table-column prop="publishTime" label="发布时间" width="180" />
        
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="handleAudit(scope.row)" 
              v-if="scope.row.status === '0'"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 新增需求对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增需求"
      width="600px"
      @close="closeAddDialog"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="需求标题" prop="title">
          <el-input v-model="addForm.title" placeholder="请输入需求标题" />
        </el-form-item>
        
        <el-form-item label="需求描述" prop="description">
          <el-input
            v-model="addForm.description"
            type="textarea"
            placeholder="请输入需求描述"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="预算(元)" prop="budget">
          <el-input v-model.number="addForm.budget" placeholder="请输入预算金额" />
        </el-form-item>
        
        <el-form-item label="截止日期" prop="deadline">
          <el-date-picker
            v-model="addForm.deadline"
            type="date"
            placeholder="请选择截止日期"
            style="width: 100%"
          />
        </el-form-item>
        

      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAddDialog">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑需求对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑需求"
      width="600px"
      @close="closeEditDialog"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="需求标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入需求标题" />
        </el-form-item>
        
        <el-form-item label="需求描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            placeholder="请输入需求描述"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="预算(元)" prop="budget">
          <el-input v-model.number="editForm.budget" placeholder="请输入预算金额" />
        </el-form-item>
        
        <el-form-item label="截止日期" prop="deadline">
          <el-date-picker
            v-model="editForm.deadline"
            type="date"
            placeholder="请选择截止日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeEditDialog">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 审核需求对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="审核需求"
      width="400px"
      @close="closeAuditDialog"
    >
      <el-form
        ref="auditFormRef"
        :model="auditForm"
        :rules="auditRules"
        label-width="80px"
      >
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item 
          label="审核备注" 
          prop="auditRemark"
        >
          <el-input
            v-model="auditForm.auditRemark"
            type="textarea"
            placeholder="请输入审核备注"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAuditDialog">取消</el-button>
          <el-button type="primary" @click="submitAuditForm">确认审核</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useDemandManagement } from '@/hooks/useDemandManagement';

// 使用需求管理Hook
const {
  loading,
  demandData,
  pagination,
  searchParams,
  fetchDemandData,
  handleSearch,
  handleReset,
  handleSizeChange,
  handleCurrentChange,
  addDemand,
  updateDemand,
  deleteDemand,
  auditDemand,
  getStatusText,
  getStatusTagType
} = useDemandManagement();

// 搜索表单
const searchForm = reactive({
  title: '',
  status: ''
});

// 监听搜索表单变化，同步到searchParams
Object.keys(searchForm).forEach(key => {
  Object.defineProperty(searchForm, key, {
    get() {
      return searchParams[key];
    },
    set(value) {
      searchParams[key] = value;
    }
  });
});

// 新增需求表单数据
const addForm = reactive({
  title: '',
  description: '',
  budget: null,
  deadline: ''
});

// 编辑需求表单数据
const editForm = reactive({
  id: '',
  title: '',
  description: '',
  budget: null,
  deadline: ''
});

// 审核需求表单数据
const auditForm = reactive({
  status: '1',
  auditRemark: ''
});

// 对话框可见性
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const auditDialogVisible = ref(false);
const currentAuditId = ref(null);

// 表单引用
const addFormRef = ref();
const editFormRef = ref();
const auditFormRef = ref();

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入需求标题', trigger: 'blur' },
    { min: 2, max: 200, message: '需求标题长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入需求描述', trigger: 'blur' },
    { min: 5, max: 2000, message: '需求描述长度在 5 到 2000 个字符', trigger: 'blur' }
  ],
  budget: [
    { required: true, message: '请输入预算金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '预算金额必须大于0', trigger: 'blur' }
  ],
  deadline: [
    { required: true, message: '请选择截止日期', trigger: 'change' }
  ],
  // userId和userType从上下文获取，不需要前端验证

}

// 审核表单校验规则
const auditRules = {
  status: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  auditRemark: [
    { required: (rule, value, callback) => {
      if (auditForm.status === '2' && !value) {
        callback(new Error('拒绝时必须填写审核备注'));
      } else {
        callback();
      }
    }, trigger: 'blur' }
  ]
};

// 打开新增对话框
const openAddDialog = () => {
  addDialogVisible.value = true;
};

// 关闭新增对话框
const closeAddDialog = () => {
  addDialogVisible.value = false;
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  // 重置表单数据
Object.assign(addForm, {
  title: '',
  description: '',
  budget: null,
  deadline: ''
});
};

// 提交新增需求表单
const submitAddForm = async () => {
  if (!addFormRef.value) return;
  
  try {
    // 表单校验
    await addFormRef.value.validate();
    
    // 准备提交数据 - 与后端API保持一致，用户信息从上下文获取，不需要前端传递
    const submitData = {
      title: addForm.title,
      description: addForm.description,
      budget: addForm.budget,
      deadline: addForm.deadline
    };
    
    // 提交数据
    await addDemand(submitData);
    
    // 显示成功提示
    ElMessage.success('新增需求成功');
    
    // 重新获取需求列表
    await fetchDemandData();
    
    // 关闭对话框
    closeAddDialog();
    
  } catch (error) {
    // 表单校验失败或提交失败
    if (error !== false) { // error === false 是表单校验失败的返回值
      ElMessage.error('提交失败：' + (error.message || '未知错误'));
    }
  }
};

// 打开编辑对话框
const openEditDialog = (row) => {
  // 填充表单数据
  Object.assign(editForm, {
    id: row.id,
    title: row.title || '',
    description: row.description || '',
    budget: row.budget || null,
    deadline: row.deadline || ''
  });
  // 显示对话框
  editDialogVisible.value = true;
};

// 关闭编辑对话框
const closeEditDialog = () => {
  editDialogVisible.value = false;
  if (editFormRef.value) {
    editFormRef.value.resetFields();
  }
  // 重置表单数据
  Object.assign(editForm, {
    id: '',
    title: '',
    description: '',
    budget: null,
    deadline: ''
  });
};

// 提交编辑需求表单
const submitEditForm = async () => {
  if (!editFormRef.value) return;
  
  try {
    // 表单校验
    await editFormRef.value.validate();
    
    // 准备提交数据
    const submitData = {
      title: editForm.title,
      description: editForm.description,
      budget: editForm.budget,
      deadline: editForm.deadline
    };
    
    // 提交数据
    await updateDemand(editForm.id, submitData);
    
    // 显示成功提示
    ElMessage.success('编辑需求成功');
    
    // 重新获取需求列表
    await fetchDemandData();
    
    // 关闭对话框
    closeEditDialog();
    
  } catch (error) {
    // 表单校验失败或提交失败
    if (error !== false) { // error === false 是表单校验失败的返回值
      console.error('提交表单失败:', error);
    }
  }
};

// 打开审核对话框
const openAuditDialog = (row) => {
  currentAuditId.value = row.id;
  // 重置审核表单
  Object.assign(auditForm, {
    status: '1',
    auditRemark: ''
  });
  // 显示对话框
  auditDialogVisible.value = true;
};

// 关闭审核对话框
const closeAuditDialog = () => {
  auditDialogVisible.value = false;
  if (auditFormRef.value) {
    auditFormRef.value.resetFields();
  }
  currentAuditId.value = null;
};

// 提交审核表单
const submitAuditForm = async () => {
  if (!auditFormRef.value || !currentAuditId.value) return;
  
  try {
    // 表单校验
    await auditFormRef.value.validate();
    
    // 提交审核 - 与后端API保持一致，使用对象方式传递参数
    await auditDemand({
      id: currentAuditId.value,
      status: auditForm.status,
      auditRemark: auditForm.auditRemark
    });
    
    // 显示成功提示
    ElMessage.success('审核成功');
    
    // 重新获取需求列表
    await fetchDemandData();
    
    // 关闭对话框
    closeAuditDialog();
    
  } catch (error) {
    // 表单校验失败或提交失败
    if (error !== false) { // error === false 是表单校验失败的返回值
      ElMessage.error('审核失败：' + (error.message || '未知错误'));
    }
  }
};

// 编辑需求
const handleEdit = (row) => {
  openEditDialog(row);
};

// 删除需求
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除需求「${row.title}」吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteDemand(row.id);
      ElMessage.success('删除成功');
      await fetchDemandData();
    } catch (error) {
      console.error('删除失败:', error);
    }
  }).catch(() => {
    // 取消删除
  });
};

// 审核需求
const handleAudit = (row) => {
  openAuditDialog(row);
};

// 页面挂载时获取数据
onMounted(() => {
  fetchDemandData();
});
</script>

<style scoped>
.demand-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: #303133;
}

.search-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.search-form .el-form-item:last-child {
  margin-left: 10px;
}

.table-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.title-cell {
  display: flex;
  flex-direction: column;
}

.title-text {
  font-weight: 500;
  margin-bottom: 5px;
}

.description-text {
  font-size: 12px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>